#!/usr/bin/env python

from conf.config import ConfigParser
from browser.driver import BrowserOption, BrowserDriver

from tqdm import tqdm
from collections import deque
import os
import sys
import time
import msvcrt

# 解决中文乱码问题 TODO 研究为什么能解决
# sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

''' GLOBAL VARIABLE AREA '''
CUR_PATH = os.getcwd()
CFG_PARSER = ConfigParser(os.getcwd())

STU_DAILY_WORK_URLS = [
    ("22.Yeenle", "https://gitee.com/yenleeee/daily-record/blob/master/DailyRecord.txt"),
    ("22.Zhangyixuan", "https://gitee.com/zyx2004/daily-record/edit/master/study.md"),
    ("22.Jinjingjing", "https://gitee.com/jinjing1234/daily-record/blob/master/D"),
    ("22.Huangyijiong", "https://gitee.com/hyj555/daliy-record/blob/master/a.git.txt"),

    ("21.Zhangqiang", "https://gitee.com/zhangqiangyyy/daily-record/blob/master/ZQ")
]


def fill_login(dri):
    if len(dri.find_elements('id', 'user_login')) > 0:
        dri.find_element('id', 'user_login').send_keys(CFG_PARSER.get_username().replace('\r', '').replace('\n', ''))
        dri.find_element('id', 'user_password').send_keys(CFG_PARSER.get_password().replace('\r', '').replace('\n', ''))
        dri.find_element('name', 'commit').click()
        time.sleep(3)
    return dri


def crawl_executor(stu, url):
    browser_kind = CFG_PARSER.get_browser_kind().removesuffix('\n')
    opt = BrowserOption(browser_kind).get_handler()
    dri = BrowserDriver(browser_kind, opt).get_handler()
    dri.get(url)
    fill_login(dri)

    content = dri.find_element('xpath', '//textarea').get_attribute('value')
    cur_file = os.path.join(CUR_PATH, "output", stu+".md")
    with open(cur_file, 'a', encoding='utf-8') as s:
        s.write(content)
    dri.quit()
    return cur_file
    

# num值需要注意用户的输入范围
def parseLatestContent(file_path, num=10):
    flag = False
    for line in list(deque(open(file_path, encoding='utf-8'), num)):
        if flag or "STM32F10X" in line:
            flag = True
            print(line)        


if __name__ == "__main__":
    print('*** Welcome to Use Students Daily-Work Collector. ***\n')
    file_path = ""
    output_path = os.path.join(CUR_PATH, "output")
    if not os.path.isdir(output_path):
        os.mkdir(output_path)

    loader = tqdm(STU_DAILY_WORK_URLS, desc='[爬取作业] => ', file=sys.stdout)
    for l in loader:
        file_path = crawl_executor(l[0], l[1])

    print('\n*** Job Finished, See U Again. ***')
    print("按任意键返回。")
    msvcrt.getwche()
        